package com.aidex.web.controller.commodity;

import com.aidex.business.domain.BCategory;
import com.aidex.business.service.BCategoryService;
import com.aidex.common.annotation.Log;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.TreeNode;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品类目表Controller
 * @author 1205560870@qq.com
 * @email 1205560870@qq.com
 * @date 2025-03-10
 */
@RestController
@RequestMapping("/category/bCategory")
public class BCategoryController extends BaseController {

    @Autowired
    private BCategoryService bCategoryService;
    
    /**
     * 根据层级展开部门树表格
     * @param level 展开层级
     * @param id 起始展开ID
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/{level}/{id}")
    public R list(@PathVariable("level") @NotEmpty int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }
        //默认为根节点
        if (StringUtils.isEmpty(id)) {
            id = Constants.TREE_ROOT;
        }
        List<BCategory> depts = bCategoryService.listDataByLevel(level, id);
        return R.data(depts);
    }
    /**
     * 部门树表格检索
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/searchDeptList")
    public R searchDeptList (BCategory BCategory)
    {
        List<BCategory> depts =  bCategoryService.searchDeptList(BCategory);
        return R.data(depts);
    }
    /**
     * 根据ID获取部门信息
     * @param id
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{id}")
    public R detail(@NotBlank @PathVariable String id) {
        BCategory BCategory = bCategoryService.get(id);
        BCategory parentDept = bCategoryService.get(BCategory.getParentId());
        if(parentDept != null){
//            BCategory.setParentName(parentDept.getCategoryName());
//            BCategory.setParentDeptType(parentDept.getDeptType());
        }
        return R.data(BCategory);
    }

    /**
     * 获取当前父节点下最大编号
     * @param parentId
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:post:query')")
    @Log(title = "岗位管理", businessType = BusinessType.SELECT)
    @GetMapping("/findMaxSort/{parentId}")
    public R findMaxSort(@PathVariable("parentId") String parentId) {
        BCategory BCategory = new BCategory();
        BCategory.setParentId(parentId);
        return R.data(bCategoryService.findMaxSort(BCategory));
    }

    /**
     * 校验同一个父部门下是否存在同名的部门
     * @param deptName 部门名称
     * @param parentId 父部门ID
     * @param id
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:post:edit')")
    @Log(title = "部门管理", businessType = BusinessType.CHECK)
    @GetMapping(value = {"/validateDeptNameUnique/{deptName}/{parentId}/{id}", "/validateDeptNameUnique/{deptName}/{parentId}"})
    public R validateDeptNameUnique(@NotBlank(message = "部门名称不允许为空") @PathVariable("deptName") String deptName, @NotBlank(message = "ID不允许为空")  @PathVariable("parentId") String parentId, @PathVariable(value = "id", required = false) String id) {
//        BCategory BCategory = new BCategory();
//        BCategory.setParentId(parentId);
//        BCategory.setDeptName(deptName);
//        BCategory.setId(id);
//        bCategoryService.checkDeptNameUnique(BCategory);
//        return R.status(Boolean.TRUE);
          return null;
    }
    /**
     * 新增部门
     * @param dept
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "类目管理", businessType = BusinessType.INSERT)
    @PostMapping("/addCategory")
    public R addCategory(@RequestBody @Validated  BCategory category) {
        System.out.println(category);
        bCategoryService.save(category);
        return R.data(category);
    }

    /**
     * 修改部门
     * @param dept
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated  BCategory dept) {
        bCategoryService.save(dept);
        return R.data(dept);
    }

    /**
     * 删除部门
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public R remove(@PathVariable  String id) {
        BCategory BCategory = new BCategory();
        BCategory.setId(id);
        return R.status(bCategoryService.remove(BCategory));
    }

    /**
     * 部门选择树
     * @param level 初始展开层级
     * @param id 展开节点ID
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/listTree/{level}/{id}")
    public R listTree(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }
        //默认为根节点
        if (StringUtils.isEmpty(id)) {
            id = Constants.TREE_ROOT;
        }
        List<TreeNode> depts = bCategoryService.buildDeptTree(level, id);
        return R.data(depts);
    }
    /**
     * 部门树检索
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/search")
    public R search (BCategory BCategory)
    {
//        List<TreeNode> depts =  bCategoryService.search(BCategory.getDeptName());
//        return R.data(depts);
        return  null;
    }

    /**
     * 部门选择树
     * @param level
     * @param id
     * @param excludeId 排除节点
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping(value = {"/listTreeExcludeChild/{level}/{id}/{excludeId}"})
    public R listTreeExcludeChild(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id, @PathVariable(value = "excludeId",required = false) String excludeId) {
        if (level == 0) {
            level = 2;
        }
        //默认为根节点
        if (StringUtils.isEmpty(id)) {
            id = Constants.TREE_ROOT;
        }
        List<TreeNode> depts = bCategoryService.buildDeptTreeExcludeChild(10, id,excludeId);
        return R.data(depts);
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public R roleDeptTreeselect(@PathVariable("roleId") String roleId) {
        List<BCategory> depts = bCategoryService.findList(new BCategory());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", bCategoryService.selectDeptListByRoleId(roleId));
        ajax.put("depts", bCategoryService.buildDeptTreeExcludeChild(-1, Constants.TREE_ROOT,null));
        return R.data(ajax);
    }

    /**
     * 选人页面按部门加载
     * @param level 初始展开层级
     * @param id 展开节点ID
     * @return
     */
    @GetMapping("/userSelectList/{level}/{id}")
    public R userSelectList(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }
        //默认为根节点
        if (StringUtils.isEmpty(id)) {
            id = Constants.TREE_ROOT;
        }
        List<TreeNode> depts = bCategoryService.buildDeptSelectUserTree(level, id);
        return R.data(depts);
    }
    /**
     * 按部门树检索用户
     */
    @GetMapping("/searchDeptUserList")
    public R searchDeptUserList (BCategory BCategory)
    {
        List<TreeNode> depts =  bCategoryService.searchDeptUserList(BCategory);
        return R.data(depts);
    }


    /**
     * 通用选人页面根据用户ID
     * @return
     */
    @PostMapping(value = { "/getDeptInfoByIds"})
    public R getDeptInfoByIds(@Validated @RequestBody JSONObject deptIdsObj)
    {
        List<Map<String,Object>> BCategoryList = bCategoryService.getDeptInfoByIds(deptIdsObj);
        return R.data(BCategoryList);
    }

    /**
     * 刷新缓存
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "类目管理", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public R refreshCache() {
        bCategoryService.refreshCache();
        return R.status(true);
    }

    /**
     * 导出商品类目表列表
     */
    @PreAuthorize("@ss.hasPermi('category:bCategory:export')")
    @Log(title = "商品类目表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(BCategory bCategory) {
        List<BCategory> list = bCategoryService.findList(bCategory);
        ExcelUtil<BCategory> util = new ExcelUtil<BCategory>(BCategory.class);
        return util.exportExcel(list, "商品类目表数据");
    }

}